/**
 * AdminAccessInterceptor.java
 * 
 * Copyright@2015 OVT Inc. All rights reserved. 
 * 
 * May 12, 2015
 */
package com.ovt.doorbell.payment.api.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.ovt.doorbell.payment.common.model.JsonDocument;
import com.ovt.doorbell.payment.dao.constant.UserRole;
import com.ovt.doorbell.payment.dao.vo.User;
import com.ovt.doorbell.payment.service.context.SessionContext;
import com.ovt.doorbell.payment.service.exception.ServiceErrorCode;

/**
 * AdminAccessInterceptor: do admin authorization
 * 
 * @Author zhi.liu
 * @Version 1.0
 * @See
 * @Since [OVT Cloud Platform]/[API] 1.0
 */
public class AdminAccessInterceptor extends HandlerInterceptorAdapter
{
    /*
     * (non-Javadoc)
     * 
     * @see
     * org.springframework.web.servlet.handler.HandlerInterceptorAdapter#preHandle
     * (javax.servlet.http.HttpServletRequest,
     * javax.servlet.http.HttpServletResponse, java.lang.Object)
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception
    {
        super.preHandle(request, response, handler);

        User user = SessionContext.getCurrentUser();
        if (user.getRole() != UserRole.ADMIN)
        {
            JsonDocument respBody =
                    new JsonDocument(ServiceErrorCode.NO_ACCESS, "No access!");

            // Spring internal json converter
            MappingJackson2HttpMessageConverter converter =
                    new MappingJackson2HttpMessageConverter();
            converter.write(respBody, MediaType.APPLICATION_JSON,
                    new ServletServerHttpResponse(response));

            return false;
        }

        return true;
    }
}
